import os
import cgi
import datetime
import wsgiref.handlers
import random
import cProfile

from google.appengine.ext import db
from google.appengine.ext import webapp
from google.appengine.api import users
from google.appengine.ext.webapp import template

#========== MODELS ==========
class User(db.Model):
    name = db.StringProperty()
    email = db.EmailProperty()
    accountType = db.StringProperty()
    
class Question(db.Model):
    #author = db.ReferenceProperty(User)
    author = db.IntegerProperty()
    text = db.StringProperty()
    date = db.DateProperty()
    answers = db.StringListProperty()
    quantityOfAnswers = db.ListProperty(int)
    correctAnswer = db.IntegerProperty()

class AnswerBind(db.Model):
    user = db.ReferenceProperty(User)
    #user = db.UserProperty()
    question = db.ReferenceProperty(Question)
    answer = db.IntegerProperty()
    date = db.DateProperty()
#========== MODELS ==========

#==========
#class Answer():
 #   str test
    
  #  def __init__(self, atext):
   #     text = "Answer"
    #    quantityOfAnswers = 0
#==========

#========== PAGES ==========
class MainPage(webapp.RequestHandler):
  def get(self):
    user = users.get_current_user()
    
    if user:
      #self.response.headers['Content-Type'] = 'text/plain'
      template_values = {"User": user.nickname()}
    else:
      template_values = {}
      self.redirect(users.create_login_url(self.request.uri))
    
    path = os.path.join(os.path.dirname(__file__), 'index.html')
    self.response.out.write(template.render(path, template_values))

class NewQuestion(webapp.RequestHandler):
  def get(self):
    user = users.get_current_user()
    
    if user:
      #self.response.headers['Content-Type'] = 'text/plain'
      template_values = {"User": user.nickname()}
    else:
      template_values = {}
      self.redirect(users.create_login_url(self.request.uri))
      
    path = os.path.join(os.path.dirname(__file__), 'newquestion.html')
    self.response.out.write(template.render(path, template_values))

class AddQuestion(webapp.RequestHandler):
  def post(self):
    user = users.get_current_user()
    
    if user:
      #self.response.headers['Content-Type'] = 'text/plain'
      template_values = {"User": user.nickname()}

      question = Question()
      
      question.author = user
      question.text = self.request.get("question")
      question.answers = [self.request.get("ans1"), self.request.get("ans2"), self.request.get("ans3")]
      question.put()
    else:
      template_values = {}
      self.redirect(users.create_login_url(self.request.uri))
      
    path = os.path.join(os.path.dirname(__file__), 'addquestion.html')
    self.response.out.write(template.render(path, template_values))

class CheckQuestion(webapp.RequestHandler):
  def get(self):
    user = users.get_current_user()
    
    if user:
      #self.response.headers['Content-Type'] = 'text/plain'
      questions = db.GqlQuery("SELECT * FROM Question WHERE author = :1", user)
      template_values = {"User": user, "Questions": questions}
      #question = Question()
      
      #for q in questions:
        #question = q
        
      #template_values = {"User": user.nickname(), "Question": question.Text, "Ans1": question.Answers[0], "Ans2": question.Answers[1], "Ans3": question.Answers[2]}
    else:
      template_values = {}
      self.redirect(users.create_login_url(self.request.uri))
      
    path = os.path.join(os.path.dirname(__file__), 'checkquestion.html')
    self.response.out.write(template.render(path, template_values))

class Generator(webapp.RequestHandler):
  def get(self):
    template_values = {}
    path = os.path.join(os.path.dirname(__file__), 'generator.html')
    self.response.out.write(template.render(path, template_values))
    
class Generate(webapp.RequestHandler):
  def post(self):
    text = self.request.get("question")

    al1 = "abcdefghijklmnopqrstuvwxyz"
    n = ""
    q = ""
    i = 0
    l = 0
    text = text.lower()
    p = 0
    u[0] = User()

    for g in range(1, 100):
      u[g] = User()
      
    #u[0] = User()
    #for w in text:
      #if w not in al1:
        #text = text.replace(w, "")
        
    for w in text:
      if i == 5:
        if p > 100:
          break
        
        u[p] = User()
        u[p].name = n
        u[p].email = n + "@gmail.com"
        u[p].put()
        p += 1
        i = 0
        n = ""
      else:
        if w not in al1:
          continue
        n += w
        i = i + 1

    #pWARNING(u)
    """for w in text:
      if l == 20:
        qu = Question()
        qu.text = q
        qu.answers = ["a1", "a2", "a3"]
        qu.author = random.randint(0, 10000)
        qu.put()
        l = 0
        q = ""
      else:
        l += 1
        q += w"""
    
    template_values = {}
    path = os.path.join(os.path.dirname(__file__), 'generate.html')
    self.response.out.write(template.render(path, template_values))

def pWARNING(u):
    u.put()
#========== PAGES ==========

application = webapp.WSGIApplication([
  ('/', MainPage),
  ('/newquestion', NewQuestion),
  ('/addquestion', AddQuestion),
  ('/checkquestion', CheckQuestion),
  ('/generate', Generate),
  ('/generator', Generator)
], debug=True)


def main2():
  wsgiref.handlers.CGIHandler().run(application)

def main():
 # This is the main function for profiling 
 # We've renamed our original main() above to real_main()
 import cProfile, pstats
 prof = cProfile.Profile()
 prof = prof.runctx("main2()", globals(), locals())
 print "<pre>"
 stats = pstats.Stats(prof)
 stats.sort_stats("time")  # Or cumulative
 stats.print_stats(600)  # 80 = how many to print
 # The rest is optional.
 # stats.print_callees()
 # stats.print_callers()
 print "</pre>"


if __name__ == '__main__':
  main()
